// functionPage/pages/operatorInfo/countryList/countryList.js
import throttle from '../../../../utils/throttle.js';
import Http from '../../../../utils/http.js';
const http = new Http();

const app = getApp();
// 滚动高度
let scrollTopInside = 0;

// city-bar-item据顶部高度
let barToTop;

// 每个索引bar的高度
let itemHeight;

// 后面滚动区域有所修改，可以认为是scroll-view顶部距离屏幕顶部的高度
let switchBottom = 0;
Page({
    /**
     * 页面的初始数据
     */
    data: {
        id: '',
        isPower: false,
        ipxBottom: 0,
        // 所有的区域列表
        allAreaObject: {},
        allArea: [],
        indexList: [],
        // 右侧激活的首字母索引
        activeAnchorIndex: null,
        balanceValue: false, //对比显示
        showSelectAll: true, //显示全部
        selectAll: false, //对比全选
        selectNum: 0, //是否选择了
        selectId: [],
        selectIdArr: [],
        //操作弹框
        show: false,
        actions: [],
    },
    //添加运营商
    jumpAddTap(e) {
        wx.navigateTo({
            url: `../../../../releasePage/pages/addOperator/addOperator`,
        });
    },
    jumpBalanceTap(e) {
        let jump = false;
        let arr = [];
        for (let i = 0; i < this.data.selectIdArr.length; i++) {
            if (this.data.selectIdArr[i] && this.data.selectIdArr[i].length) {
                jump = true;
            }
        }
        if (this.data.selectAll) {
            jump = true;
        }
        if (!jump) return;
        for (let i = 0; i < this.data.selectIdArr.length; i++) {
            if (this.data.selectIdArr[i]) {
                for (let j = 0; j < this.data.selectIdArr[i].length; j++) {
                    arr.push(this.data.selectIdArr[i][j]);
                }
            }
        }
        console.log(arr);
        let id = arr.toString();
        console.log(id);
        let pages = getCurrentPages(); //当前页面栈
        let prevPage = pages[pages.length - 2]; //上一页面（项目组详情页面）
        if (!this.data.selectAll) {
            prevPage.setData({
                id: id,
            });
            prevPage.balanceInfo();
        } else {
            prevPage.setData({
                id: '',
            });
            prevPage.refresh();
        }
        wx.navigateBack({
            delta: 1,
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getRegionList('allAreaObject', 'allArea', 'indexList');
        if (app.globalData.isIpx) {
            this.setData({
                ipxBottom: 34,
            });
        }
        if (
            app.globalData.authority == '00' ||
            app.globalData.authority == '01'
        ) {
            this.setData({
                isPower: true,
            });
        }
    },
    refresh() {
        this.getRegionList('allAreaObject', 'allArea', 'indexList');
    },
    // 获取所有城市和地区
    getRegionList(objName, arrName, indexName) {
        let _that = this;
        http.getRequest(
            `cjMap/getCityOperatorContactList?authId=${app.globalData.authId}`
        ).then((res) => {
            if (res.status == 0) {
                wx.setNavigationBarTitle({
                    title: '全球运营商·' + res.operatorCount,
                });
                // 获取所有首字母数据，并将有数据的城市和索引放入相关的数组中
                _that.setData(
                    {
                        [objName]: res.data,
                    },
                    () => {
                        // 定义一个暂时的空数组
                        let tempRecordCity = [];
                        let tempIndexList = [];
                        for (let key of Object.keys(_that.data[objName])) {
                            if (_that.data[objName][key].length > 0) {
                                tempRecordCity.push(_that.data[objName][key]);
                                tempIndexList.push(key);
                            }
                        }
                        // 数据处理完成后再去获取对应元素的高度等数据
                        _that.setData(
                            {
                                [arrName]: tempRecordCity,
                                [indexName]: tempIndexList,
                            },
                            () => {
                                _that.getElementData();
                            }
                        );
                    }
                );
            }
        });
    },

    onBarTouchMove(e) {
        const sidebarLength = this.data.indexList.length;
        const touch = e.touches[0];
        console.log(touch.clientY, barToTop);
        let index = Math.floor((touch.clientY - barToTop) / itemHeight);
        if (index < 0) {
            index = 0;
        } else if (index > sidebarLength - 1) {
            index = sidebarLength - 1;
        }
        this.scrollToAnchor(index);
        console.log(index);
    },
    onBarTouchStop(e) {
        this.setData({
            activeAnchorIndex: null,
        });
    },
    scrollToAnchor(index) {
        if (
            typeof index !== 'number' ||
            this.data.activeAnchorIndex === index
        ) {
            return;
        }
        this.setData({
            activeAnchorIndex: index,
        });

        let query = wx.createSelectorQuery();
        query.select(`.record-city-index${index}`).boundingClientRect();
        query.selectViewport().scrollOffset();

        query.exec((res) => {
            console.log(res);
            this.setData(
                {
                    scrollTop: scrollTopInside + res[0].top - switchBottom,
                },
                () => {
                    scrollTopInside =
                        scrollTopInside + res[0].top - switchBottom;
                    console.log(scrollTopInside);
                }
            );
        });
    },
    onScroll(e) {
        // 监听滚动事件
        scrollTopInside = e.detail.scrollTop;
    },

    // 获取相关元素高度等数据
    getElementData() {
        let queryCityBarItem = wx.createSelectorQuery();
        queryCityBarItem.select('.city-bar-item0').boundingClientRect();
        queryCityBarItem.exec((res) => {
            itemHeight = res[0].height;
        });

        let queryCityBar = wx.createSelectorQuery();
        queryCityBar.select('.city-bar-national').boundingClientRect();
        queryCityBar.exec((res) => {
            barToTop = res[0].top;
        });
    },

    chooseArea(e) {
        console.log(e);
        let {
            pinyinsimple,
            pinyindetail,
            countryorarea,
        } = e.currentTarget.dataset;
        let pages = getCurrentPages(); //当前页面栈
        let prevPage = pages[pages.length - 2]; //上一页面
        prevPage.setData(
            {
                pinyinsimple,
                pinyindetail,
                countryOrArea: countryorarea,
            },
            () => {
                wx.navigateBack({
                    detal: 1,
                });
            }
        );
    },
    // 对比
    selectBalance(e) {
        this.setData({
            balanceValue: !this.data.balanceValue,
        });
    },
    checkboxChange(e) {
        let _that = this;
        console.log(e.target.dataset.index);
        let index = [];
        for (let i = 0; i < index.length; i++) {
            if ((index[i] = e.target.dataset.index)) {
                index.push(e.target.dataset.index);
            }
        }
        let name = 'selectIdArr[' + e.target.dataset.index + ']';
        _that.setData({
            [name]: e.detail.value,
        });
        let selectNumber = 0;
        for (let i = 0; i < _that.data.selectIdArr.length; i++) {
            if (_that.data.selectIdArr[i] && _that.data.selectIdArr[i].length) {
                selectNumber = selectNumber + _that.data.selectIdArr[i].length;
            }
        }
        _that.setData({
            selectNum: selectNumber,
        });
        console.log(_that.data.selectIdArr);
    },
    //全选
    selectAll(e) {
        this.setData({
            selectAll: true,
            showSelectAll: false,
        });
    },
    //全不选
    removeAll(e) {
        this.setData({
            selectAll: false,
            showSelectAll: true,
            selectNum: 0,
            selectIdArr: [],
        });
    },
    // 设为Top弹框
    setTop(e) {
        let action = [];
        if (e.target.dataset.topcount == 0) {
            action = [
                {
                    name: '设为Top1',
                    color: '#333333',
                },
            ];
        }
        if (e.target.dataset.topcount == 1) {
            action = [
                {
                    name: '设为Top1',
                    color: '#333333',
                },
                {
                    name: '设为Top2',
                    color: '#333333',
                },
            ];
        }
        if (e.target.dataset.topcount == 2) {
            action = [
                {
                    name: '设为Top1',
                    color: '#333333',
                },
                {
                    name: '设为Top2',
                    color: '#333333',
                },
                {
                    name: '设为Top3',
                    color: '#333333',
                },
            ];
        }
        this.setData({
            show: true,
            actions: action,
            id: e.target.dataset.id,
        });
    },
    cancelTap(e) {
        if (
            app.globalData.authority != '00' &&
            app.globalData.authority != '01'
        )
            return;
        this.setData({
            show: true,
            actions: [
                {
                    name: '取消Top',
                    color: '#FF455E',
                },
            ],
            id: e.target.dataset.id,
        });
    },
    //显示弹出层
    editBtn(e) {
        this.setData({
            show: true,
        });
    },
    //取消
    onCancel(e) {
        this.setData({
            show: false,
        });
    },
    onDelect(e) {
        let _that = this;
        console.log(e.detail.name);
        if (e.detail.name == '设为Top1') {
            wx.request({
                url: app.globalData.rootPath + `cjMap/setCityOperatorTop`,
                method: 'GET',
                data: {
                    authId: app.globalData.authId,
                    id: _that.data.id,
                    istop: '01',
                    toplevel: 1,
                },
                success: function (res) {
                    wx.showToast({
                        title: '设置成功',
                        icon: 'success',
                        duration: 1500,
                    });
                    _that.getRegionList(
                        'allAreaObject',
                        'allArea',
                        'indexList'
                    );
                },
            });
        } else if (e.detail.name == '设为Top2') {
            wx.request({
                url: app.globalData.rootPath + `cjMap/setCityOperatorTop`,
                method: 'GET',
                data: {
                    authId: app.globalData.authId,
                    id: _that.data.id,
                    istop: '01',
                    toplevel: 2,
                },
                success: function (res) {
                    wx.showToast({
                        title: '设置成功',
                        icon: 'success',
                        duration: 1500,
                    });
                    _that.getRegionList(
                        'allAreaObject',
                        'allArea',
                        'indexList'
                    );
                },
            });
        } else if (e.detail.name == '设为Top3') {
            wx.request({
                url: app.globalData.rootPath + `cjMap/setCityOperatorTop`,
                method: 'GET',
                data: {
                    authId: app.globalData.authId,
                    id: _that.data.id,
                    istop: '01',
                    toplevel: 3,
                },
                success: function (res) {
                    wx.showToast({
                        title: '设置成功',
                        icon: 'success',
                        duration: 1500,
                    });
                    _that.getRegionList(
                        'allAreaObject',
                        'allArea',
                        'indexList'
                    );
                },
            });
        } else if (e.detail.name == '取消Top') {
            wx.request({
                url: app.globalData.rootPath + `cjMap/setCityOperatorTop`,
                method: 'GET',
                data: {
                    authId: app.globalData.authId,
                    id: _that.data.id,
                    istop: '00',
                },
                success: function (res) {
                    wx.showToast({
                        title: '取消成功',
                        icon: 'success',
                        duration: 1500,
                    });
                    _that.getRegionList(
                        'allAreaObject',
                        'allArea',
                        'indexList'
                    );
                },
            });
        }
        _that.setData({
            show: false,
        });
    },
});
